package tools

import (
	"gitee.com/dsler-go/utils/model/rand"
	rand2 "math/rand"
	"time"
)

const (
	RandPrize = iota
	WinPrize
	NotWinPrize
)

func GetItemByRandom(data []rand.RandomItem, isWin int) rand.RandomItem {
	noLottery := rand.RandomItem{}
	lotteryPer := int64(0)
	totalPer := int64(0)
	tmpTotal := make([]rand.RandomItem, 0)
	tmpLottery := make([]rand.RandomItem, 0)
	for _, v := range data {
		totalPer = totalPer + v.Per
		tmpTotal = append(tmpTotal, v)
		if v.Qty <= 0 {
			continue
		}
		if !v.Flag {
			noLottery = v
		} else {
			lotteryPer = lotteryPer + v.Per
			tmpLottery = append(tmpLottery, v)
		}
	}
	if lotteryPer <= 0 {
		return noLottery
	}
	switch isWin {
	case WinPrize: // 必中
		rand2.NewSource(time.Now().UnixNano())
		randomIndex := rand2.Intn(int(lotteryPer))
		tmpPer := int64(0)
		for k, v := range tmpLottery {
			if k == len(tmpLottery)-1 {
				return v
			}
			if randomIndex > int(tmpPer+v.Per) {
				tmpPer = tmpPer + v.Per
				continue
			}
			return v
		}
	case NotWinPrize: // 必不中
		return noLottery
	default:
		if totalPer <= 0 {
			return noLottery
		}
		rand2.NewSource(time.Now().UnixNano())
		randomIndex := rand2.Intn(int(totalPer))
		tmpPer := int64(0)
		isLottery := true
		for k, v := range tmpTotal {
			if k == len(tmpTotal)-1 {
				if !v.Flag {
					isLottery = false
					break
				}
			}
			if randomIndex <= int(tmpPer+v.Per) {
				if !v.Flag {
					isLottery = false
				}
				break
			}
			tmpPer = tmpPer + v.Per
		}
		if isLottery {
			rand2.NewSource(time.Now().UnixNano())
			randomIndex2 := rand2.Intn(int(lotteryPer))
			tmpPer2 := int64(0)
			for k, v := range tmpLottery {
				if k == len(tmpLottery)-1 {
					return v
				}
				if randomIndex2 > int(tmpPer2+v.Per) {
					tmpPer2 = tmpPer2 + v.Per
					continue
				}
				return v
			}
		}
	}
	return rand.RandomItem{}
}
